import {Application} from "pinus";
import {ControlService} from "../../services/controlService";

let controlConfig:ControlConfig = null

// 统一创建对象接口
export default function (app: Application) {
    if (controlConfig === null) {
        controlConfig = new ControlConfig(app)
    }
    return controlConfig
}

export class ControlConfig {
    private _controlService: ControlService
    private _id: number
    private _reserve: number
    private _rebate: number
    private _progress: number

    constructor(private app: Application) {
        this._controlService = app.get('controlService')
        this._reserve = 0
        this._rebate = 0
        this._progress = 0
    }
    public get reserve() {
        return this._reserve
    }
    public get rebate() {
        return this._rebate
    }
    public get progress() {
        return this._progress
    }
    public get id() {
        return this._id
    }
    public set progress(value: number) {
        this._progress = value
    }

    public finished() {
        return this._progress >= this._reserve
    }

    public async load(): Promise<boolean> {
        const config = await this._controlService.getControlConfig()
        if (!config){
            return false
        }
        this._id = config.id
        this._reserve = config.reserve
        this._rebate = config.rebate
        this._progress = config.progress
        return true
    }
    public async reload(): Promise<boolean> {
        const config = await this._controlService.getControlConfig()
        if (!config){
            return false
        }
        this._id = config.id
        this._reserve = config.reserve
        this._rebate = config.rebate
        this._progress = config.progress
        return true
    }

    public async saveProgress(progress: number) {
        this.progress += progress
        return this._controlService.saveProgress(this._progress,this._id)
    }

}
